﻿// IOCP_Client.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <WinSock2.h>
#include "ServerLogAdapter.h"

#pragma comment(lib,"ws2_32.lib")

using namespace std;

char g_buffer[1024];

int InitializeNetWorlk()
{
    WSADATA wsaData = {0};
    int nRet = WSAStartup(MAKEWORD(2, 2), &wsaData);
    cout << "WSAStartup() nRet=" << nRet << endl;
    if (nRet != NO_ERROR)
    {
        int nErr = WSAGetLastError();
        return 1;
    }

    sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(6000);
    server.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
    SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    //cout << "socket() hSocket=" << hex << hSocket << endl;
    TRACESVR("socket() hSocket = %u", hSocket);
    nRet = connect(hSocket, (sockaddr*)&server, sizeof(server));
    cout << "connect() nRet=" << nRet << endl;
    if (nRet < 0)
    {
        int nErr = WSAGetLastError();
        cout << "error:" << nErr << endl;
        WSACleanup();
        return 2;
    }

    int nSendCount = 0;

    while (true)
    {
        memset(g_buffer, NULL, sizeof(g_buffer));
        sprintf_s(g_buffer, sizeof(g_buffer), "Send Test Count = %d", nSendCount++);
        //strcpy(g_buffer, "hello");
        nRet = send(hSocket, g_buffer, strlen(g_buffer) + 1, 0);
        if (nRet == SOCKET_ERROR)
        {
            //10054 0x2746 远程主机强迫关闭了一个现有的连接。 
            int nErr = WSAGetLastError();
            cout << "SOCKET_ERROR:" << dec << nErr << endl;
            break;
        }
        memset(g_buffer, NULL, sizeof(g_buffer));
        int nRet = recv(hSocket, g_buffer, 1024, 0);
        //cout << "recv() nRet=" << nRet << ", g_buffer = " << g_buffer << endl;
        TRACESVR("[RECV BUFF] nRet = %d, g_buffer = %s", nRet, g_buffer);
        if (nRet == SOCKET_ERROR)
        {
            int nErr = WSAGetLastError();
            cout << "SOCKET_ERROR:" << dec << nErr << endl;
            break;
        }
        Sleep(1000);
    }

    nRet = closesocket(hSocket);
    cout << "closesocket() nRet=" << nRet << endl;
    nRet = WSACleanup();
    cout << "WSACleanup() nRet=" << nRet << endl;

    return 0;
}

int main()
{
    InitializeNetWorlk();
    std::cout << "Hello World!\n";
    system("pause");
}

// 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单
// 调试程序: F5 或调试 >“开始调试”菜单

// 入门使用技巧: 
//   1. 使用解决方案资源管理器窗口添加/管理文件
//   2. 使用团队资源管理器窗口连接到源代码管理
//   3. 使用输出窗口查看生成输出和其他消息
//   4. 使用错误列表窗口查看错误
//   5. 转到“项目”>“添加新项”以创建新的代码文件，或转到“项目”>“添加现有项”以将现有代码文件添加到项目
//   6. 将来，若要再次打开此项目，请转到“文件”>“打开”>“项目”并选择 .sln 文件
